import React, { useEffect, useState } from 'react';
import { Row, Col, message, Spin } from 'antd';
import PubSub from 'pubsub-js';
import GGEditor, { Flow, RegisterEdge } from 'gg-editor';
import { connect } from 'dva';
import { FlowContextMenu } from './components/EditorContextMenu';
import { FlowToolbar } from './components/EditorToolbar';
import { FlowItemPanel } from './components/EditorItemPanel';
import { FlowDetailPanel } from './components/EditorDetailPanel';
import CustomNode from './CustomNode';
import CustomEnd from './CustomEnd';
import request from '@/utils/request';
import styles from './style.less';

const namespace = 'flowConfig';
GGEditor.setTrackable(false);

// canvasObj 为流程配置的主体信息，obj为流程管理版本跳转传递的数据
function FlowPage({ size: { height }, goToStep, obj, refresh, canvasObj, dispatch }) {
  const [loading, setLoading] = useState(false);
  const [detail, setDetail] = useState([]);

  // 卸载清楚dva里的默认值
  const saveCanvas = params => {
    dispatch({
      type: `${namespace}/saveCanvas`,
      payload: params,
    });
  };

  useEffect(() => {
    setLoading(true);
    request('pmc/pms/PmOrderFlowDefController/get', {
      data: {
        flowId: obj.flowId,
      },
      method: 'GET',
    })
      .then(res => {
        if (res.success) {
          if (res.data.detail) {
            setDetail(JSON.parse(res.data.detail));
          }
          saveCanvas({
            flowName: res.data.flowName,
            flowCode: res.data.flowCode,
            version: res.data.version,
            limitValue: res.data.limitValue,
            alertValue: res.data.alertValue,
            timeUnit: res.data.timeUnit || undefined,
          });
        } else {
          message.error(res.errMessage);
        }
      })
      .always(() => {
        setLoading(false);
      });
    return saveCanvas({
      flowName: '',
      flowCode: '',
      version: '',
      limitValue: '',
      alertValue: '',
      timeUnit: undefined,
    });
  }, []);

  const handleSave = node => {
    // 获取FlowDetailPanel流程配置信息的数据
    const paramsObj = {
      ...canvasObj,
      flowId: obj.flowId,
      detail: JSON.stringify(node),
    };
    // console.log(node);
    // 流程复制
    if (obj.operType === 'draw') {
      setLoading(true);
      request('pmc/pms/PmOrderFlowDefController/update', {
        data: paramsObj,
      })
        .then(res => {
          if (res.success) {
            message.success('流程绘制成功！');
            goToStep(1);
            refresh();
          } else {
            message.error(res.errMessage);
          }
        })
        .always(() => setLoading(false));
    } else if (obj.operType === 'copy') {
      setLoading(true);
      request('pmc/pms/PmOrderFlowDefController/add', {
        data: {
          ...paramsObj,
          packageId: obj.packageId,
          catalogId: obj.catalogId,
        },
      })
        .then(res => {
          if (res.success) {
            message.success('流程复制成功！');
            goToStep(1);
            refresh();
          } else {
            message.error(res.errMessage);
          }
        })
        .always(() => setLoading(false));
    }
  };

  // const config = {
  //   getStyle(item) {
  //     const model = item.getModel();
  //     const { color, size } = model;
  //     return {
  //       stroke: color || '#A3B1BF',
  //       lineWidth: size || 1,
  //       startArrow: false,
  //       endArrow: true,
  //     };
  //   },
  //   getActivedStyle(item) {
  //     return {
  //       lineWidth: 2,
  //       stroke: '#1890ff',
  //     };
  //   },
  //   getSelectedStyle(item) {
  //     return {
  //       lineWidth: 2,
  //       stroke: '#1890ff',
  //     };
  //   },
  // };

  return (
    <Spin spinning={loading}>
      <GGEditor className={styles.editor}>
        <Row className={styles.editorHd}>
          <Col span={24}>
            <FlowToolbar handleSave={handleSave} goToStep={goToStep} obj={obj} />
          </Col>
        </Row>
        <Row>
          <Col span={4} className={styles.editorSidebar} style={{ height: `${height - 45}px` }}>
            <FlowItemPanel />
          </Col>
          {/* 预览的时候给个遮罩蒙板 */}
          {obj.operType === 'view' ? (
            <Col span={4} style={{ height: `${height - 45}px` }} className={styles.zhe_zhao} />
          ) : null}
          <Col span={16} style={{ height: `${height - 45}px` }}>
            <Flow
              style={{ height: `${height - 45}px` }}
              graph={{ edgeDefaultShape: 'flow-polyline' }}
              data={detail}
              align={{
                line: {
                  stroke: '#1890ff', // 对齐线颜色
                  lineWidth: 1, // 对齐线宽度
                },
              }}
            />
            <CustomNode />
            <CustomEnd />
            {/* <RegisterEdge name="custom-edge" config={config} extend="flow-polyline" /> */}
          </Col>
          <Col span={4} className={styles.editorSidebar} style={{ height: `${height - 45}px` }}>
            <FlowDetailPanel />
          </Col>
        </Row>
        {obj.operType !== 'view' ? <FlowContextMenu /> : null}
      </GGEditor>
    </Spin>
  );
}

export default connect(({ setting, flowConfig }) => ({
  size: setting.size,
  canvasObj: flowConfig.canvasObj,
}))(FlowPage);
